﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using TnPlusSmsWinService.SmsSender;

using VPBS.Informix.DAL;
using VPBS.SqlClient.DAL;
using TnPlus.Biz;
using TnPlus.Entities.Models;

namespace TnPlusSmsWinService
{
    public partial class TnPlusSmsWinService : ServiceBase
    {
        System.Timers.Timer timer;
        EventLog eventLog;
        public TnPlusSmsWinService()
        {
            InitializeComponent();

            // Reads settings from app.config
            this.ServiceName = ConfigurationSettings.AppSettings["serviceName"];
            string eventLogName = ConfigurationSettings.AppSettings["eventLogName"];
            string eventLogSource = ConfigurationSettings.AppSettings["eventLogSource"];

            // Initializes eventlog
            if (!EventLog.SourceExists(eventLogSource))
                EventLog.CreateEventSource(eventLogSource, eventLogName);

            eventLog = new EventLog();
            ((System.ComponentModel.ISupportInitialize)(eventLog)).BeginInit();

            eventLog.Source = eventLogSource;

            // Registers the application
            eventLog.Log = eventLogName;

            ((System.ComponentModel.ISupportInitialize)(eventLog)).EndInit();

            //CollectAndSendSms();
        }

        protected override void OnStart(string[] args)
        {
            eventLog.WriteEntry("+++++++++++++ START SMS SERVICE +++++++++++++", EventLogEntryType.Warning);

            // Runs the process every X minutes
            int interval = Int32.Parse(ConfigurationSettings.AppSettings["interval"]) * 1000;
            timer = new System.Timers.Timer();
            timer.Interval = interval;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(CollectAndSendSms);
            timer.Start();
        }

        protected void InsertToHistory(string IdCommon)
        {
            PortfolioHistoryInfo portfolioHistoryInfo = new PortfolioHistoryInfo();
            CashHistoryInfo cashHistoryInfo = new CashHistoryInfo();
            DebtHistoryInfo debtHistoryInfo = new DebtHistoryInfo();
            CallSMSHistoryInfo callSMSHistoryInfo = new CallSMSHistoryInfo();

            PortfolioHistoryService portfolioHistoryService = new PortfolioHistoryService();
            CashHistoryService cashHistoryService = new CashHistoryService();
            DebtHistoryService debtHistoryService = new DebtHistoryService();
            CallSMSHistoryService callSMSHistoryService = new CallSMSHistoryService();

            DataTable Da = new DataTable();

            //Insert into PortfolioHistory
            Da = TnPlusVCustomerInfoDAL.Get_PortfolioToday_With_IdCommon(IdCommon);
            if (Da != null && Da.Rows.Count > 0)
            {
                for (int l = 0; l < Da.Rows.Count; l++)
                {

                    portfolioHistoryInfo.IdPortfolio = new Guid(Da.Rows[l]["IdPortfolio"].ToString());
                    portfolioHistoryInfo.PostDate = DateTime.Parse(Da.Rows[l]["PostDate"].ToString());
                    portfolioHistoryInfo.IdCommon = Da.Rows[l]["IdCommon"].ToString();
                    portfolioHistoryInfo.AccountNo = Da.Rows[l]["AccountNo"].ToString();
                    portfolioHistoryInfo.SecSymbol = Da.Rows[l]["SecSymbol"].ToString();
                    portfolioHistoryInfo.SecType = Da.Rows[l]["SecType"].ToString();
                    portfolioHistoryInfo.Unit = Int32.Parse(Da.Rows[l]["Unit"].ToString());
                    portfolioHistoryInfo.PriceMkt = decimal.Parse(Da.Rows[l]["PriceMkt"].ToString());
                    portfolioHistoryInfo.IMStock = decimal.Parse(Da.Rows[l]["IMStock"].ToString());
                    portfolioHistoryInfo.IMCustomer = decimal.Parse(Da.Rows[l]["IMCustomer"].ToString());
                    portfolioHistoryInfo.AdjustRate = decimal.Parse(Da.Rows[l]["AdjustRate"].ToString());
                    portfolioHistoryService.Insert(portfolioHistoryInfo);
                }
            }

            //Insert into CashHistory
            Da = TnPlusVCustomerInfoDAL.Get_CashToday_With_IdCommon(IdCommon);
            if (Da != null && Da.Rows.Count > 0)
            {
                for (int l = 0; l < Da.Rows.Count; l++)
                {
                    cashHistoryInfo.IdCash = new Guid(Da.Rows[l]["IdCash"].ToString());
                    cashHistoryInfo.PostDate = DateTime.Parse(Da.Rows[l]["PostDate"].ToString());
                    cashHistoryInfo.IdCommon = Da.Rows[l]["IdCommon"].ToString();
                    cashHistoryInfo.AccountNo = Da.Rows[l]["AccountNo"].ToString();
                    cashHistoryInfo.Cash = decimal.Parse(Da.Rows[l]["Cash"].ToString());
                    cashHistoryInfo.SecType = Da.Rows[l]["SecType"].ToString();
                    cashHistoryService.Insert(cashHistoryInfo);
                }
            }

            //Insert into DebtHistory
            Da = TnPlusVCustomerInfoDAL.Get_DebtToday_With_IdCommon(IdCommon);
            if (Da != null && Da.Rows.Count > 0)
            {
                for (int l = 0; l < Da.Rows.Count; l++)
                {
                    debtHistoryInfo.IdDebt = new Guid(Da.Rows[l]["IdDebt"].ToString());
                    debtHistoryInfo.PostDate = DateTime.Parse(Da.Rows[l]["PostDate"].ToString());
                    debtHistoryInfo.IdCommon = Da.Rows[l]["IdCommon"].ToString();
                    debtHistoryInfo.AccountNo = Da.Rows[l]["AccountNo"].ToString();
                    debtHistoryInfo.Debt = decimal.Parse(Da.Rows[l]["Debt"].ToString());
                    debtHistoryService.Insert(debtHistoryInfo);
                }
            }

            //Insert into CallSMSHistory
            Da = TnPlusCallSmsDAL.Get_CallSMS_With_IdCommon(IdCommon);
            if (Da != null && Da.Rows.Count > 0)
            {
                for (int l = 0; l < Da.Rows.Count; l++)
                {
                    callSMSHistoryInfo.IdCallSMS = new Guid(Da.Rows[l]["IdCallSMS"].ToString());
                    callSMSHistoryInfo.PostDate = DateTime.Parse(Da.Rows[l]["PostDate"].ToString());
                    callSMSHistoryInfo.IdCommon = Da.Rows[l]["IdCommon"].ToString();
                    callSMSHistoryInfo.AccountNo = Da.Rows[l]["AccountNo"].ToString();
                    callSMSHistoryInfo.Asset = decimal.Parse(Da.Rows[l]["Asset"].ToString());
                    callSMSHistoryInfo.Debt = decimal.Parse(Da.Rows[l]["Debt"].ToString());
                    callSMSHistoryInfo.Ratio = decimal.Parse(Da.Rows[l]["Ratio"].ToString());
                    callSMSHistoryInfo.CallLMV = decimal.Parse(Da.Rows[l]["CallLMV"].ToString());
                    callSMSHistoryInfo.ForceLMV = decimal.Parse(Da.Rows[l]["ForceLMV"].ToString());
                    callSMSHistoryInfo.Action = Da.Rows[l]["Action"].ToString();
                    callSMSHistoryInfo.AddCash = decimal.Parse(Da.Rows[l]["AddCash"].ToString());
                    callSMSHistoryInfo.ContentSMS = Da.Rows[l]["ContentSMS"].ToString();
                    callSMSHistoryInfo.ReceiveNo = Da.Rows[l]["ReceiveNo"].ToString();
                    try
                    {
                        callSMSHistoryInfo.Status = bool.Parse(Da.Rows[l]["Status"].ToString());
                    }catch
                    {
                        callSMSHistoryInfo.Status = null;
                    }
                    callSMSHistoryService.Insert(callSMSHistoryInfo);
                }
            }
        }

        protected void CollectAndSendSms(object obj, System.Timers.ElapsedEventArgs e)
        {
            int startHour = Int32.Parse(ConfigurationSettings.AppSettings["startTime"]);
            int stopHour = Int32.Parse(ConfigurationSettings.AppSettings["stopTime"]);
            DateTime now = DateTime.Now;
            string strMinute = now.Minute.ToString();
            if (now.Minute < 10) strMinute = "0" + now.Minute.ToString();
            int Time = int.Parse(now.Hour.ToString() + strMinute);

            if ((Time >= 0 && Time < startHour) || (Time >= stopHour && Time <= 2300) ||
                ThdHolydayDateDAL.CheckOfHolydayDate() == true)
            {
                if (now.Hour == Int16.Parse(ConfigurationSettings.AppSettings["stopTime"].Substring(0, 2)) + 3)
                {
                    DataTable daCallSMS = TnPlusCallSmsDAL.Get_CallSMSToday();
                    if (daCallSMS != null && daCallSMS.Rows.Count > 0)
                    {
                        //Insert vao lich su Call
                        for (int k = 0; k < daCallSMS.Rows.Count; k++)
                        {
                            this.InsertToHistory(daCallSMS.Rows[k]["IdCommon"].ToString());
                        }
                    }
                    else
                    {
                        //Insert vao lich su luot transfer cuoi cung cua ngay
                        this.InsertToHistory(TnPlusVCustomerInfoDAL.Get_LastIdCommon());
                    }
                    //Delete DeleteSMSSender
                    TnPlusVCustomerInfoDAL.DeleteSMSSender();
                }
                return;
            }

            SmsSender.Service ObjVPBSSender = new SmsSender.Service();
            if (TnPlusCallSmsDAL.Select_WaitToSendSMSLst() != null &&
                TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows.Count > 0)
            {
                bool Result = false;
                string Phone = "";
                string Content = "";
                string AccountNo = "";
                string AcctNotSend = null;
                string[] arrNumsCC;
                for (int i = 0; i < TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows.Count; i++)
                {
                    Phone = TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows[i]["ReceiveNo"].ToString();
                    Content = TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows[i]["ContentSMS"].ToString();
                    AccountNo = TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows[i]["AccountNo"].ToString();
                    try
                    {
                        AcctNotSend = new AcctListNotSendMessageService().Select(AccountNo).AccountNo;
                    }
                    catch (Exception)
                    {

                        AcctNotSend = null;
                    }
                    
                    //Send to Customer
                    if (AcctNotSend == null)
                        Result = ObjVPBSSender.SendSMS(Phone, Content);

                    
                    //Send to CC
                    if (
                        Int16.Parse(
                            TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows[i]["AccountNo"].ToString().Substring(0, 1)) ==
                        0)
                        arrNumsCC = ConfigurationSettings.AppSettings["ccNumsHN"].Split('|');
                    else if (
                        Int16.Parse(
                            TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows[i]["AccountNo"].ToString().Substring(0,
                                                                                                                 2)) ==
                        18)
                        arrNumsCC = ConfigurationSettings.AppSettings["ccNumsDN"].Split('|');
                    else
                        arrNumsCC = ConfigurationSettings.AppSettings["ccNumsHCM"].Split('|');
                    foreach (string num in arrNumsCC)
                    {
                        if (num != null && num.Length >= 8 && AcctNotSend == null)
                        {
                            ObjVPBSSender.SendSMS(num, Content);
                        }
                    }

                    //Send to Admin
                    arrNumsCC = ConfigurationSettings.AppSettings["ccNumsAdmin"].Split('|');
                    foreach (string num in arrNumsCC)
                    {
                        if (num != null && num.Length >= 8 && AcctNotSend == null)
                        {
                            ObjVPBSSender.SendSMS(num, Content);
                        }
                    }
                    TnPlusCallSmsDAL.Update_Status(
                        TnPlusCallSmsDAL.Select_WaitToSendSMSLst().Rows[i]["IdCallSMS"].ToString(), Result.ToString());
                }
            }
        }

        protected override void OnStop()
        {
            eventLog.WriteEntry("+++++++++++++ STOP SMS SERVICE +++++++++++++", EventLogEntryType.Warning);
        }
    }
}
